﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class UserControl_ControlDoiGiaHangBan : System.Web.UI.UserControl
{
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (ViewState["flag"] == null)
            {
                //ViewState["flag"] = false;
                ClearAdd();
            }
            txtDate.Text = Session["workingday"].ToString();
            BindGridSearch(Session["sitecode"].ToString());
        }
        gridProductEmpty();
        MessageBox.ShowOnPageLoad = false;
    }

    void ClearAdd()
    {
        txtSoNV.Text = "New";

        txtDate.Text = Session["workingday"].ToString();

        if (ViewState["KhoHangTemp"] != null)
        {
            ViewState["KhoHangTemp"] = null;

        }
        BindKhoiTao();        

        ViewState["flag"] = true;
        TabContainer1.ActiveTabIndex = 0;

        lblMsg.Text = "";
        lblMsg.Visible = false;
        btnDelete.Visible = false;
        btnSave.Text = "Lưu";
    }
    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        ClearAdd();
        
    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
      
    }
    public int CompareDate(string sdate1, string sdate2)
    {
        DateTime date1 = new DateTime(int.Parse(sdate1.Substring(6, 4)), int.Parse(sdate1.Substring(3, 2)), int.Parse(sdate1.Substring(0, 2)));
        DateTime date2 = new DateTime(int.Parse(sdate2.Substring(6, 4)), int.Parse(sdate2.Substring(3, 2)), int.Parse(sdate2.Substring(0, 2)));
        int result = DateTime.Compare(date1, date2);
        return result;

        //if (result < 0)
        //    relationship = "sdate1 is earlier than";
        //else if (result == 0)
        //    relationship = "is the same time as";
        //else
        //    relationship = "sdate 1 is later than";

    }
        
    protected void grvSearch_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {
                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblSoNV = (Label)grv.FindControl("lblSoNV");

                DataTable db = dt.Get_Data_DataTable(str, ref error, "TTr_getDetailChangePrice", CommandType.StoredProcedure,
                   new SqlParameter("@DocNo", lblSoNV.Text));
                txtSoNV.Text = db.Rows[0]["docno"].ToString();
                txtDate.Text = db.Rows[0]["DocDate"].ToString();

                ViewState["KhoHangTemp"] = db;

                grvProduct.DataSource = db;
                grvProduct.DataBind();

                grvSearch.DataSource = null;
                grvSearch.DataBind();

                ViewState["flag"] = false;
                TabContainer1.ActiveTabIndex = 0;
                
                lblMsg.Text = "";
                lblMsg.Visible = false;
                btnSave.Text = "Cập nhật";
                btnDelete.Visible = true;

            }
        }
        catch (Exception ex)
        {
          
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   
    }
   
    protected void grvProduct_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();
            TextBox txtGM = (TextBox)grvProduct.Rows[e.RowIndex].FindControl("txtGM");
            if ((txtGM.Text == "") || (txtGM.Text == "0"))
            {
                txtGM.Text = "1";
            }
            Double NewPrice = Double.Parse(txtGM.Text);
            DataTable table = new DataTable();
            table = (DataTable)ViewState["KhoHangTemp"];

            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == keys)
                {
                    dr[3] = NewPrice;
                    table.AcceptChanges();
                    ViewState["KhoHangTemp"] = table;

                    grvProduct.EditIndex = -1;
                    grvProduct.DataSource = ViewState["KhoHangTemp"];
                    grvProduct.DataBind();
                }
            }

        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();

        DataTable table = new DataTable();
        table = (DataTable)ViewState["KhoHangTemp"];

        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            if (dr[0].ToString() == keys)
            {
                table.Rows[i].Delete();
                table.AcceptChanges();
                ViewState["KhoHangTemp"] = table;
                grvProduct.EditIndex = -1;
                //Kiểm tra xem nếu đã xóa hết
                if (table.Rows.Count > 0)
                {
                    grvProduct.DataSource = ViewState["KhoHangTemp"];
                    grvProduct.DataBind();
                }
                else
                {
                    BindKhoiTao();
                }
                
                return;
            }
            i++;
        }
    }
    protected void grvProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grvProduct.EditIndex = -1;
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
    }
    protected void grvProduct_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grvProduct.EditIndex = e.NewEditIndex;
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
    }
    protected void grvProduct_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvProduct.PageIndex = e.NewPageIndex;
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();
    }
    void BindGridSearch(string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getMasterChangePrice", CommandType.StoredProcedure,
                 new SqlParameter("@type", "F"),
                new SqlParameter("@siteCode", sitecode));
            grvSearch.DataSource = db;
            grvSearch.DataBind();
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvSearch.PageIndex = e.NewPageIndex;
        BindGridSearch(Session["sitecode"].ToString());
    }
    protected void ImgBtnRequest_Click(object sender, ImageClickEventArgs e)
    {

        BindGridSearch(Session["sitecode"].ToString());
    }
    //void BindGridProduct()
    //{
    //    dt = new ClassExecute.ClassExecute();
    //    DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getProductForChangePrice", CommandType.StoredProcedure,
    //        new SqlParameter("@sitecode", Session["sitecode"].ToString()));
    //    if (db.Rows.Count > 0)
    //    {
    //        grvProduct.DataSource = db;
    //        ViewState["KhoHangTemp"] = db;
    //    }
    //    else
    //    {
           
    //        grvProduct.DataSource = null;
    //    }
    //    grvProduct.DataBind();
    //}

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (grvProduct.Rows.Count > 0)
        {
            int checkkhoaso = CompareDate(txtDate.Text, Session["workingday"].ToString());
            if (checkkhoaso < 0)
            {
                //ShowMessageBox("Ngày bạn chọn nhỏ hơn ngày đã khóa sổ trong hệ thống,ngày khóa sổ của bạn là " + Session["workingday"].ToString());
                lblMsg.Text = "Ngày bạn chọn nhỏ hơn ngày đã khóa sổ trong hệ thống,ngày khóa sổ của bạn là " + Session["workingday"].ToString();
                lblMsg.Visible = true;
                txtDate.Focus();
            }
            else
            {
                dt = new ClassExecute.ClassExecute();
                try
                {

                    string docno = "";
                    if ((bool)ViewState["flag"])
                    {
                        docno = dt.GetDataDepend(str, "[k_getDocNoChangPrice]", CommandType.StoredProcedure, ref error,
                            new SqlParameter("@sitecode", Session["sitecode"].ToString()));
                        ViewState["flag"] = true;
                    }
                    else
                    {
                        docno = txtSoNV.Text;
                    }

                    int i = 1;
                    DataTable dtLisProduct = new DataTable();
                    dtLisProduct = (DataTable)ViewState["KhoHangTemp"];
                    foreach (DataRow dr in dtLisProduct.Rows)
                    {
                        //Label lblMaHang = (Label)grv.FindControl("lblMaHang");

                        //Label lblGiaCu = (Label)grv.FindControl("lblGiaCu");
                        //Label lblGiaMoi = (Label)grv.FindControl("lblGiaMoi");
                        string strGiaMoi = dr["Giá mới"].ToString();
                        string strGiaCu = dr["Giá cũ"].ToString();


                        if (float.Parse(strGiaMoi)!=float.Parse(strGiaCu))
                        {
                        bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_inssertNVChangePrice", ref error,
                            new SqlParameter("@itemkey", dr["Mã hàng"].ToString()),
                            new SqlParameter("@docno", docno),
                            new SqlParameter("@Type", "F"),
                            new SqlParameter("@docdate", txtDate.Text),
                            new SqlParameter("@stocprice", float.Parse(strGiaMoi)),
                            new SqlParameter("@stockcost", float.Parse(strGiaCu)),
                            new SqlParameter("@sitecode", Session["sitecode"].ToString()),
                            new SqlParameter("@i", i));
                        }
                       
                        i++;
                    }

                   
                        if (ViewState["KhoHangTemp"] != null)
                        {
                            ViewState["KhoHangTemp"] = null;

                        }

                        ClearAdd();


                        txtDate.Text = Session["workingday"].ToString();
                        txtSoNV.Text = "";
                        txtDate.Text = "";


                        //ShowMessageBox("Nghiệp vụ đổi giá thành công");
                        lblMsg.Text = "Nghiệp vụ đổi giá thành công";
                        lblMsg.Visible = true;
                    
                }
                catch (Exception ex)
                {

                    string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
                }
            }
        }
        else
        {
            //ShowMessageBox("Nghiệp vụ chưa được khởi tạo");
            lblMsg.Text = "Nghiệp vụ chưa được khởi tạo";
            lblMsg.Visible = true;
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if ((txtSoNV.Text != "") && (txtSoNV.Text != null))
            {
                bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_deleteChangeprice", ref error,
                     new SqlParameter("@DocNo", txtSoNV.Text));
                if (kq)
                {

                    grvProduct.DataSource = null;
                    grvProduct.DataBind();
                    if (ViewState["KhoHangTemp"] != null)
                    {
                        ViewState["KhoHangTemp"] = null;

                    }
                    txtSoNV.Text = "";


                    
                    //ShowMessageBox("Nghiệp vụ xóa thành công");
                    ClearAdd();
                    lblMsg.Text = "Nghiệp vụ xóa thành công";
                    lblMsg.Visible = true;
                }
                else
                {
                    //ShowMessageBox("Hệ thống đang bảo trì");
                    lblMsg.Text = "Hệ thống đang bảo trì";
                    lblMsg.Visible = true;
                }
            }
            else
            {
                //ShowMessageBox("Nghiệp vụ chưa được khởi tạo");
                lblMsg.Text = "Nghiệp vụ chưa được khởi tạo";
                lblMsg.Visible = true;
            }
        }
        catch (Exception ex)
        {
            //ShowMessageBox("Hệ thống đang bảo trì");
            lblMsg.Text = "Hệ thống đang bảo trì";
            lblMsg.Visible = true;
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   

    }

    protected void txtMaHangInput_TextChanged(object sender, EventArgs e)
    {

        try
        {
            gridProductEmpty();

            TextBox txtMaMHInput = grvProduct.FooterRow.FindControl("txtMaHangInput") as TextBox;
            Label lblTenHangInput = grvProduct.FooterRow.FindControl("lblTenHangInput") as Label;
            Label lblGiaCuInPut = grvProduct.FooterRow.FindControl("lblGiaCuInput") as Label;
            TextBox txtGiaMoiInput = grvProduct.FooterRow.FindControl("txtGMInput") as TextBox;
            
            
            //FillGrid();
            if (!txtMaMHInput.Text.Equals(String.Empty))
            {
                string str1 = txtMaMHInput.Text;
                int index = str1.IndexOf("|");
                //if (index == -1)
                {
                    dt = new ClassExecute.ClassExecute();

                    DataTable dtMH = dt.Get_Data_DataTable(str, ref error, "TTr_getProductForChangePrice", CommandType.StoredProcedure,
                        new SqlParameter("@itemkey", str1.Substring(0, index - 1)));
                    if (dtMH.Rows.Count > 0)
                    {
                        txtMaMHInput.Text = dtMH.Rows[0]["Mã hàng"].ToString();
                        lblTenHangInput.Text = dtMH.Rows[0]["Tên hàng"].ToString();
                        lblGiaCuInPut.Text = dtMH.Rows[0]["Giá cũ"].ToString();
                        txtGiaMoiInput.Text = dtMH.Rows[0]["Giá mới"].ToString();
                        
                    }
                    else
                    {
                        txtMaMHInput.Focus();
                        return;
                    }
                }
                //else
                //{
                //    txtMaMHInput.Text = str1.Substring(0, index - 1);
                //    txtTenHangInput.Text = str1.Substring(index + 2, str1.Length - index - 2);
                //}

                txtGiaMoiInput.Focus();

            }

        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);

        }
    }

    protected void txtGMInput_TextChanged(object sender, EventArgs e)
    {
        gridProductEmpty();

        AddRowToGridProduct();
        TextBox txtMaHangInput = grvProduct.FooterRow.FindControl("txtMaHangInput") as TextBox;
        txtMaHangInput.Focus();
    }

    void gridProductEmpty()
    {
        if (grvProduct.Rows[0].Cells[0].Text == "Thêm mặt hàng")
        {
            int TotalColumns = grvProduct.Rows[0].Cells.Count;
            grvProduct.Rows[0].Cells.Clear();
            grvProduct.Rows[0].Cells.Add(new TableCell());
            grvProduct.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            grvProduct.Rows[0].Cells[0].Text = "Thêm mặt hàng";
        }
    }

    void BindKhoiTao()
    {
        try
        {            

            DataTable dtChiTietDH = new DataTable();
            dtChiTietDH = dtChiTietDonHang();

            ViewState["KhoHangTemp"] = dtChiTietDonHang();

            dtChiTietDH.Rows.Add(dtChiTietDH.NewRow());
            dtChiTietDH.Rows[0][0] = "";
            dtChiTietDH.Rows[0][1] = "";
            dtChiTietDH.Rows[0][2] = "";
            dtChiTietDH.Rows[0][3] = "";
            grvProduct.DataSource = dtChiTietDH;
            grvProduct.DataBind();

            int TotalColumns = grvProduct.Rows[0].Cells.Count;
            grvProduct.Rows[0].Cells.Clear();
            grvProduct.Rows[0].Cells.Add(new TableCell());
            grvProduct.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            grvProduct.Rows[0].Cells[0].Text = "Thêm mặt hàng";
        }
        catch
        {
        }
    }

    private DataTable dtChiTietDonHang()
    {
        DataTable dtChiTietDH = new DataTable();
        DataColumn dtc;

        //Tao Cot Ma Hang
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Mã hàng";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot Ten Hang
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Tên hàng";
        dtChiTietDH.Columns.Add(dtc);
                
        //Tao Cot Gia Cũ
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Giá cũ";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot Giá Mới
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Giá mới";
        dtChiTietDH.Columns.Add(dtc);
                

        return dtChiTietDH;
    }

    private void AddRowToGridProduct()
    {
        gridProductEmpty();
        //Add rowd
        TextBox txtMaMHInput = grvProduct.FooterRow.FindControl("txtMaHangInput") as TextBox;
        Label lblTenHangInput = grvProduct.FooterRow.FindControl("lblTenHangInput") as Label;
        Label lblGiaCuInPut = grvProduct.FooterRow.FindControl("lblGiaCuInput") as Label;
        TextBox txtGiaMoiInput = grvProduct.FooterRow.FindControl("txtGMInput") as TextBox;

        if (txtMaMHInput.Text != "" && lblTenHangInput.Text != "")
        {
            dt = new ClassExecute.ClassExecute();
            DataTable dtMH = dt.Get_Data_DataTable(str, ref error, "TTr_getProductForChangePrice", CommandType.StoredProcedure,
                new SqlParameter("@itemkey", txtMaMHInput.Text));
            if (dtMH.Rows.Count > 0)
            {
                lblTenHangInput.Text = dtMH.Rows[0]["Tên hàng"].ToString();
                lblGiaCuInPut.Text = dtMH.Rows[0]["Giá cũ"].ToString();                
                
                if (ViewState["KhoHangTemp"] != null)
                {
                    DataTable dtCTDH = (DataTable)ViewState["KhoHangTemp"];
                    for (int i = 0; i < dtCTDH.Rows.Count; i++)
                    {
                        if (dtCTDH.Rows[i][0].ToString() == txtMaMHInput.Text)
                        {
                            dtCTDH.Rows.RemoveAt(i);
                            break;
                        }
                    }
                    DataRow dr = dtCTDH.NewRow();
                    dr[0] = txtMaMHInput.Text;
                    dr[1] = lblTenHangInput.Text;
                    dr[2] = lblGiaCuInPut.Text;
                    dr[3] = txtGiaMoiInput.Text;
                    dtCTDH.Rows.Add(dr);
                    ViewState["KhoHangTemp"] = dtCTDH;
                }
                else
                {
                    DataTable dtCTDH = dtChiTietDonHang();
                    DataRow dr = dtCTDH.NewRow();
                    dr[0] = txtMaMHInput.Text;
                    dr[1] = lblTenHangInput.Text;
                    dr[2] = lblGiaCuInPut.Text;
                    dr[3] = txtGiaMoiInput.Text;
                    dtCTDH.Rows.Add(dr);
                    ViewState["KhoHangTemp"] = dtCTDH;
                }
                grvProduct.DataSource = ViewState["KhoHangTemp"];
                grvProduct.DataBind();

                TextBox txtMaMHInputFocus = grvProduct.FooterRow.FindControl("txtMaHangInput") as TextBox;
                txtMaMHInputFocus.Focus();
            }
        }        
    }

    protected void btnAddItem_Click(object sender, EventArgs e)
    {
        AddRowToGridProduct();
    }
    protected void btnDefault_Click(object sender, EventArgs e)
    {
        AddRowToGridProduct();

    }
}